package org.compiere.model;

import java.io.File;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;

import org.compiere.apps.IProcessParameter;
import org.compiere.apps.ProcessCtl;
import org.compiere.apps.ProcessParameterPanel;
import org.compiere.process.DocAction;
import org.compiere.process.DocumentEngine;
import org.compiere.process.ProcessInfo;
import org.compiere.process.ProcessInfoParameter;
import org.compiere.util.ASyncProcess;
import org.compiere.util.CCache;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;

public class Mhrmbonus extends X_hrm_bonus implements DocAction, ASyncProcess{

	/**
	 * 
	 */
	private static final long serialVersionUID = -727926003383064111L;
	
	private int AD_Process_ID;
	/**/
	ASyncProcess m_parent;
	
	/**	Static Logger	*/
	private static CLogger	s_log	= CLogger.getCLogger (Mhrmbonus.class);

	public Mhrmbonus(Properties ctx, int hrm_bonus_ID, String trxName) {
		super(ctx, hrm_bonus_ID, trxName);
		if (hrm_bonus_ID == 0)
		{
			setDocStatus (DOCSTATUS_Drafted);		//	Draft
			setDocAction (DOCACTION_Complete);
			//
//			setPaymentRule(PAYMENTRULE_OnCredit);	//	Payment Terms
//
//			setDateInvoiced (new Timestamp (System.currentTimeMillis ()));
			setDateAcct (getDateFrom());
			setC_DocType_ID(1000063);
//			setChargeAmt (Env.ZERO);
//			setTotalLines (Env.ZERO);
//			setGrandTotal (Env.ZERO);
//			//
			setIsSOTrx (true);
//			setIsTaxIncluded (false);
			setIsApproved (false);
//			setIsDiscountPrinted (false);
//			setIsPaid (false);
//			setSendEMail (false);
//			setIsPrinted (false);
			setIsTransferred (false);
//			setIsSelfService(false);
//			setIsPayScheduleValid(false);
//			setIsInDispute(false);
			setPosted(false);
			super.setProcessed (false);
			setProcessing(false);
//			setDocumentNo(getName());
//			save();
		}
	}
	
	public Mhrmbonus(Properties ctx, ResultSet rs, String trxName) {
		super(ctx, rs, trxName);
	}
	
	/**	Bonus Lines	*/
	private  MhrmbonusLine[] m_lines;
	private X_hrm_bonusline_sub[] m_linesacct;

	/**
	 * 	Get HR Bonus Lines
	 * 	@param whereClause starting with AND
	 * 	@return lines
	 */
	private  MhrmbonusLine[] getLinesBonus (String whereClause)
	{
		String whereClauseFinal = "hrm_bonus_ID=? ";
		if (whereClause != null)
			whereClauseFinal += whereClause;
		List<X_hrm_bonusline_sub> list = new Query(getCtx(), I_hrm_bonusLine.Table_Name, whereClauseFinal, get_TrxName())
										.setParameters(gethrm_bonus_ID())
										.list();
		return list.toArray(new  MhrmbonusLine[list.size()]);
	}	//	getLines

	/**
	 * 	Get Bonus Lines
	 * 	@param requery
	 * 	@return lines
	 */
	public MhrmbonusLine[] getLinesBonus (boolean requery)
	{
		if (m_lines == null || m_lines.length == 0 || requery)
			m_lines = getLinesBonus(null);
		set_TrxName(m_lines, get_TrxName());
		return m_lines;
	}	//	getLines

	/**
	 * 	Get BOnus line
	 * 	@return lines
	 */
	public MhrmbonusLine[] getLinesBonus()
	{
		return getLinesBonus(false);
	}	//	getLines
	
	/**
	 * Get Bonus Lines assorted
	 * @param bonusID
	 * @return
	 */
	public  MhrmbonusLine[] getLinesBonusSort (int bonusID)
	{
		
		ArrayList<MhrmbonusLine> result = new ArrayList<MhrmbonusLine>();
		MhrmbonusLine line = null;
		String sql = "select * from hrm_bonusLine t \n"+
					"join c_bpartner r on r.c_bpartner_id=t.c_bpartner_id \n"+
					"where hrm_bonus_id="+bonusID+" \n"+
					"order by r.lastname";
		
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try
		{
			pstmt = DB.prepareStatement(sql, null);
			rs = pstmt.executeQuery();
			while(rs.next()){
				line = new MhrmbonusLine(getCtx(), rs, get_TrxName());
				result.add(line);
			}
		}
		catch (SQLException e)
		{
			log.log(Level.INFO, "SQL=" + sql, e);
		}
		finally {
			DB.close(rs, pstmt);
			rs = null; pstmt = null;
		}
		return result.toArray(new  MhrmbonusLine[result.size()]);
	}
	
//	 X_hrm_bonusline_sub {
	
	/**
	 * 	Get HR Bonus Lines
	 * 	@param whereClause starting with AND
	 * 	@return lines
	 */
	private X_hrm_bonusline_sub[] getLinesBonusAcct (int hrm_bonus_ID, int hrm_bonusLine_ID)	
	{
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		X_hrm_bonusline_sub result = null;
		
		ArrayList<X_hrm_bonusline_sub> list = new ArrayList<X_hrm_bonusline_sub>();
			
		// 
		String sql_ = "SELECT * FROM HRM_BONUSLINE_SUB \n " +
						"WHERE ISACTIVE='Y' \n "  +							
							" AND HRM_BONUS_ID=" + hrm_bonus_ID + " \n " +
							" AND HRM_BONUSLINE_ID=" + hrm_bonusLine_ID;
			try
			{
				pstmt = DB.prepareStatement(sql_,null);
				rs = pstmt.executeQuery();	
				while(rs.next()){
					result = new X_hrm_bonusline_sub(Env.getCtx(), rs, null);
					list.add(result);
				}				
			}
			catch (SQLException e)
			{
				s_log.log(Level.SEVERE, "product", e);
			}
			finally
			{
				DB.close(rs, pstmt);
				rs = null; pstmt = null;
			}	
			
		return list.toArray(new X_hrm_bonusline_sub[list.size()]);
	}	//	getLines	

	/**
	 * 	Get Bonus Lines
	 * 	@param requery
	 * 	@return lines
	 */
	public X_hrm_bonusline_sub[] getBonusAcctList (int hrm_bonus_ID, int hrm_bonusLine_ID, boolean requery)
	{
		if (m_linesacct == null || m_linesacct.length == 0 || requery) //2
			m_linesacct = getLinesBonusAcct(hrm_bonus_ID, hrm_bonusLine_ID);
		set_TrxName(m_linesacct, get_TrxName());		
		return m_linesacct;
	}	//	getLines	
	
	public X_hrm_bonusline_sub getBonusLine(int hrm_reservesectional_id, int hrm_bonus_ID, int hrm_bonusLine_ID, boolean isNew) {
		X_hrm_bonusline_sub result = null;
		getBonusAcctList(hrm_bonus_ID, hrm_bonusLine_ID, isNew);  //1
		for(X_hrm_bonusline_sub l:m_linesacct) {
			if (l.gethrm_reservesectional_ID() ==  hrm_reservesectional_id) {
				result = l;
				break;
			}
		}
		return result;
	}
	
//	 } X_hrm_bonusline_sub 
/// DocAction
	
	/**	Process Message 			*/
	private String		m_processMsg = null;
	/**	Just Prepared Flag			*/
	private boolean		m_justPrepared = false;
	
	
	public boolean processIt(String processAction) //throws Exception 
	{
		m_processMsg = null;
		DocumentEngine engine = new DocumentEngine (this, getDocStatus());
		return engine.processIt (processAction, getDocAction());
	}	//	process
	
	public boolean unlockIt() {
		return false;
	}
	
	public boolean invalidateIt() {
		return false;
	}
	
	public String prepareIt() {
		log.info(toString());
		m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_PREPARE);
		if (m_processMsg != null)
			return DocAction.STATUS_Invalid;

		//	Convert/Check DocType
		if (getC_DocType_ID() == 0)
		{
			m_processMsg = "No Document Type";
			return DocAction.STATUS_Invalid;
		}
		
		m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_PREPARE);
		if (m_processMsg != null)
			return DocAction.STATUS_Invalid;

		//	Add up Amounts
		m_justPrepared = true;
		if (!DOCACTION_Complete.equals(getDocAction()))
			setDocAction(DOCACTION_Complete);
		return DocAction.STATUS_InProgress;
	}	//	prepareIt	
	
	public boolean approveIt() {
		log.info(toString());
		setIsApproved(true);
		return true;
	}

	@Override
	public boolean rejectIt() {
		return false;
	}

	protected void getAD_Process_ID() {
		
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		// 
		String sql_ = "select distinct t.ad_process_id from ad_process t \n "+ 
					  "where (lower(t.value) like lower('GenerateBonusSalary%') or lower(t.name) like lower('GenerateBonusSalary%')) "+ 
				      "and t.isactive='Y'";
		try
		{
			pstmt = DB.prepareStatement(sql_, null);
			rs = pstmt.executeQuery();
			if (rs.next())
				AD_Process_ID = rs.getInt(1);
		}
		catch (SQLException e)
		{
			log.log(Level.SEVERE, "product", e);
		}
		finally
		{
			DB.close(rs, pstmt);
			rs = null; pstmt = null;
		}
	}	

	public String completeIt() {
		getAD_Process_ID();
		
//		if(AD_Process_ID != 0){
//			//  Prepare Process
//			ProcessInfo pi = new ProcessInfo ("The printing process of ", AD_Process_ID);
//			pi.setAD_User_ID (Env.getAD_User_ID(Env.getCtx()));
//			pi.setAD_Client_ID(Env.getAD_Client_ID(Env.getCtx()));
//			pi.setRecord_ID(get_ID());
//
//			List<ProcessInfoParameter> po = new ArrayList<ProcessInfoParameter>();
//			po.add(new ProcessInfoParameter("CloseTax","Y",null,"",""));
//			//
//			ProcessInfoParameter[] pp = new ProcessInfoParameter[po.size()];
//			po.toArray(pp);
//			pi.setParameter(pp);
//			//	Execute Process
//			ProcessParameterPanel pu = new ProcessParameterPanel(0, pi);
//			ProcessCtl.process(this, 0, (IProcessParameter) pu, pi, null);
//		}
		
		//	Re-Check
		if (!m_justPrepared)
		{
			String status = prepareIt();
			if (!DocAction.STATUS_InProgress.equals(status))
				return status;
		}

		m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_COMPLETE);
		if (m_processMsg != null)
			return DocAction.STATUS_Invalid;
//
//		//	Implicit Approval
		if (!isApproved())
			approveIt();
		log.info(toString());
		
		StringBuffer info = new StringBuffer();
		
		m_processMsg = info.toString().trim();
		setProcessed(true);
//		save();
		setDocAction(DOCACTION_Close);
		return DocAction.STATUS_Completed;
	} // complitIt

	@Override
	public boolean voidIt() {
		boolean result = true;
		if (!haveCorrectDocument()) {
			if ( DocAction.STATUS_Completed.equals(getDocStatus()) && isPosted()) {
				result = reverseCorrectIt();
			}
			if (result) {
				setProcessed(true);
				setDocAction(DOCACTION_None);
			}
		} else {
			result = false;
		}
		return result;	
	}

	@Override
	public boolean closeIt() {
		
		log.info(toString());
		// Before Close
		m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_BEFORE_CLOSE);
		if (m_processMsg != null)
			return false;

		setProcessed(true);
		setDocAction(DOCACTION_None);

		// After Close
		m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_AFTER_CLOSE);
		if (m_processMsg != null)
			return false;
		return true;
	}

	@Override
	public boolean reverseCorrectIt() {
		boolean result = false;
		log.info(toString());
		if (!haveCorrectDocument()) {
			result = createCorrectDocument();
		}
		return result;
	}

	@Override
	public boolean reverseAccrualIt() {
		return false;
	}

	@Override
	public boolean reActivateIt() {
		setDocStatus(STATUS_Drafted);
		setDocAction(DOCACTION_Complete);
		setProcessed(false);
		setPosted(false);
		return true;
	}

	@Override
	public String getSummary() {
		return null;
	}

	@Override
	public String getDocumentInfo() {
		return null;
	}

	@Override
	public File createPDF() {
		return null;
	}

	@Override
	public String getProcessMsg() {
		return null;
	}

	@Override
	public int getDoc_User_ID() {
		return 0;
	}

	@Override
	public BigDecimal getApprovalAmt() {
		return null;
	}/// end DocAction

	@Override
	public void lockUI(ProcessInfo pi) {
		
	}

	@Override
	public void unlockUI(ProcessInfo pi) {
		
	}

	@Override
	public boolean isUILocked() {
		return false;
	}

	@Override
	public void executeASync(ProcessInfo pi) {
		
	}
	
	public static Mhrmbonus get (Properties ctx, int hrm_bonus_ID)
	{
		Integer key = new Integer (hrm_bonus_ID);
		Mhrmbonus retValue = (Mhrmbonus) s_cache.get (key);
		if (retValue != null)
			return retValue;
		retValue = new Mhrmbonus (ctx, hrm_bonus_ID, null);
		if (retValue.get_ID () != 0)
			s_cache.put (key, retValue);
		return retValue;
	} //	get

	/**	Cache						*/
	private static CCache<Integer,Mhrmbonus>	s_cache	= new CCache<Integer,Mhrmbonus>("hrm_bonus", 20, 2);	//	2 minutes


	public static String getDocAction(Properties ctx, int hrm_bonus_ID){
	
		if(hrm_bonus_ID == 0)
			return null;
				
		String result = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		// Employee data from the card
		String sql_ = "SELECT DOCACTION FROM HRM_BONUS \n" +
						"WHERE ISACTIVE='Y' \n" +
						"AND AD_CLIENT_ID="  + Env.getAD_Client_ID(ctx) + " \n" +
						"AND HRM_BONUS_ID=" + hrm_bonus_ID + " \n"; 
		try
		{
			pstmt = DB.prepareStatement(sql_,null);
			rs = pstmt.executeQuery();
			if(rs.next())
				return rs.getString(1);		
		}
		catch (SQLException e)
		{
			s_log.log(Level.SEVERE, "product", e);
		}
		finally
		{
			DB.close(rs, pstmt);
			rs = null; pstmt = null;
		}
	
		return result;
	}
	
	@Override
	public Timestamp getDateAcct () 
	{
		if (super.getDateAcct() == null) {
			setDateAcct (getDateFrom());
		}
		return super.getDateAcct();
	}
	/**
	 * @return
	 */
	public boolean haveCorrectDocument() {
		boolean result = getReversal_ID() > 0;
		return result;
	}
	/**
	 * @return
	 */
	private boolean createCorrectDocument() {
		Mhrmbonus reversal = copyFrom (this, getDateFrom(), getDateAcct(),getC_DocType_ID(), get_TrxName());
		if (reversal == null) {
			m_processMsg = "Could not create Invoice Reversal";
			return false;
		}
		reversal.setReversal(true);
		reversal.setName("!!!!-" + reversal.getName());
		reversal.addDescription("{->" + getDocumentNo() + ")");
		reversal.sethrm_total(gethrm_total().negate());
		reversal.sethrm_percent(0 - gethrm_percent());

		MhrmbonusLine[] iLines = reversal.getLinesBonus();
		for (int i = 0; i < iLines.length; i++)
		{
			MhrmbonusLine iLine = iLines[i];
			iLine.sethrm_amountbonus(iLine.gethrm_amountbonus().negate());
			iLine.sethrm_OPV(iLine.gethrm_OPV().negate());
			iLine.sethrm_COtch(iLine.gethrm_COtch().negate());
			iLine.sethrm_IPN(iLine.gethrm_IPN().negate());
			iLine.sethrm_CNalog(iLine.gethrm_CNalog().negate());
			iLine.sethrm_total(iLine.gethrm_total().negate());
			iLine.sethrm_monthbonus(iLine.gethrm_monthbonus().negate());
			iLine.saveEx(get_TrxName());
        }
		setProcessed(true);
		
		reversal.setReversal_ID(gethrm_bonus_ID()); // TODO
		reversal.saveEx(get_TrxName());
		if (!reversal.processIt(DocAction.ACTION_Complete))	{
			m_processMsg = "Reversal ERROR: " + reversal.getProcessMsg();
			return false;
		}
		reversal.closeIt();
		reversal.setProcessing (false);
		reversal.setDocStatus(DOCSTATUS_Drafted);
		reversal.setDocAction(DOCACTION_Complete);
		reversal.saveEx(get_TrxName());
		m_processMsg = reversal.getDocumentNo();
		setReversal_ID(reversal.gethrm_bonus_ID());
		addDescription("(" + reversal.getDocumentNo() + "<-)");
		return true;
	}
	
	public void addDescription (String description)
	{
		String desc = getDescription();
		if (desc == null)
			setDescription(description);
		else
			setDescription(desc + " | " + description); 
	}	//	addDescription
	
	public static Mhrmbonus copyFrom (Mhrmbonus from, Timestamp dateDoc, Timestamp dateAcct, int C_DocTypeTarget_ID, String trxName) {
		Mhrmbonus to = new Mhrmbonus(from.getCtx(),0,trxName);
		copyValues(from, to);
		
		to.set_ValueNoCheck ("hrm_bonus_ID", I_ZERO);
		to.set_ValueNoCheck ("DocumentNo", null);
		//
		to.setDocStatus (DOCSTATUS_Drafted);		//	Draft
		to.setDocAction(DOCACTION_Complete);
		//
		to.setDateFrom (dateDoc);
		to.setDateAcct (dateAcct);
		//
		to.setIsApproved (false);
		//
		to.setIsTransferred (false);
		to.setPosted (false);
		to.setProcessed (false);
		//[ 1633721 ] Reverse Documents- Processing=Y
		to.setProcessing(false);
		//	delete references
		to.saveEx(trxName);

		//	Lines
		// Check lines exist before copy
		if ( from.getLinesBonus().length > 0 )
		{
			if (to.copyLinesBonusFrom(from) == 0)
				throw new IllegalStateException("Could not create List");
		}
		
		return to;
	}
	
	public int copyLinesBonusFrom (Mhrmbonus other) {
		if (isProcessed() || isPosted() || other == null)
			return 0;
		MhrmbonusLine[] fromLines = other.getLinesBonus(false);
		int count = 0;
		for (int i = 0; i < fromLines.length; i++)
		{
			MhrmbonusLine line = new MhrmbonusLine (getCtx(), 0, get_TrxName());
			MhrmbonusLine fromLine = fromLines[i];
			PO.copyValues (fromLine, line, fromLine.getAD_Client_ID(), fromLine.getAD_Org_ID());
			line.sethrm_bonus_ID(gethrm_bonus_ID());
			line.set_ValueNoCheck (MhrmbonusLine.COLUMNNAME_hrm_bonusLine_ID, I_ZERO);	// new
			if (line.save(get_TrxName()))
				count++;
		}
		if (fromLines.length != count)
			log.log(Level.SEVERE, "Line difference - From=" + fromLines.length + " <> Saved=" + count);
		return count;
	}
	/** Reversal Flag		*/
	private boolean m_reversal = false;

	/**
	 * 	Is Reversal
	 *	@return reversal
	 */
	public boolean isReversal()
	{
		return m_reversal;
	}	//	isReversal

	/**
	 * 	Set Reversal
	 *	@param reversal reversal
	 */
	private void setReversal(boolean reversal)
	{
		m_reversal = reversal;
	}	//	setReversal
}